package com.example.tool.util;

import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

@Service
public class RestTemplateClient {
    //
    private final RestTemplate restTemplate;

    public RestTemplateClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Retryable(
            value = {
                    HttpServerErrorException.ServiceUnavailable.class, // 503
                    ResourceAccessException.class, // 网络问题（如连接超时）
            },
            maxAttempts = 3,
            backoff = @Backoff(delay = 1000, multiplier = 2) // 指数退避
    )
    public String fetchDataFromService() {
        return restTemplate.getForObject("https://example.com/api", String.class);
    }

    @Recover
    public String recoverFromFailure(Exception ex) {
        // 所有重试失败后的降级逻辑
        return "Fallback response due to: " + ex.getMessage();
    }
}